package com.cswangdao.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.cswangdao.domain.model.MarketCoupon;
import com.cswangdao.domain.model.MarketCouponUser;
import com.cswangdao.mapper.MarketCouponMapper;
import com.cswangdao.mapper.MarketCouponUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class CouponUtil {

    @Autowired
    private MarketCouponUserMapper couponUserMapper;

    @Autowired
    private MarketCouponMapper couponMapper;

    //获取可用优惠卷
    public List<MarketCouponUser> availableCoupons(Integer userId, BigDecimal goodsTotalPrice){
        List<MarketCouponUser> couponUserList = couponUserMapper.getCouponByUserId(userId);
        if(CollUtil.isEmpty(couponUserList)){
            return null;
        }
        return couponUserList.stream().
                filter(couponUser -> isCouponEffective(
                        goodsTotalPrice,
                        couponMapper.getById(couponUser.getCouponId()),
                        couponUser)).
                toList();
    }

    //判断优惠卷是否有效
    public boolean isCouponEffective(BigDecimal goodsTotalPrice, MarketCoupon coupon, MarketCouponUser couponUser) {
        boolean flag = false;

        if(Objects.isNull(coupon)){
            return flag;
        }

        //是否达到使用门槛
        if (goodsTotalPrice.compareTo(coupon.getMin()) < 0) {
            return flag;
        }

        //优惠卷是否有效
        if (coupon.getStatus() != 0) {
            return flag;
        }

        //优惠卷是否过期
        if (coupon.getTimeType() == 0) {
            Date addTime = couponUser.getAddTime();
            short days = coupon.getDays();
            long betweenDay = DateUtil.betweenDay(addTime, new Date(), true);
            if (betweenDay >= days) {
                return flag;
            }
        }

        if (coupon.getTimeType() == 1) {
            Date now = new Date();
            if (coupon.getStartTime().after(now) || coupon.getEndTime().before(now)) {
                return flag;
            }
        }

        return !flag;
    }
}
